package com.tueye.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.tueye.base.util.Page;
import com.tueye.entity.Admin;
import com.tueye.service.IAdminInfoService;
import com.tueye.utils.DateUtils;
import com.tueye.utils.UUIDGenerator;

/**
 * 用户添加控制层操作demo
 * spring mvc 2.5 支持MultiActionController
 * @author hanxiaowei
 *
 */
@SuppressWarnings("unchecked")
@org.springframework.stereotype.Controller
@RequestMapping("/user.do")
public class AdminInfoController extends BaseController {
	private Log log = LogFactory.getLog(AdminInfoController.class);
	
	@Autowired
	@Qualifier("adminInfoService")
	private IAdminInfoService adminInfoService;
	
	//@RequestMapping(method = { RequestMethod.POST })
	@RequestMapping(params = "action=PageShow")
	public String PageShow (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// js传过来的参数列表：
		// page:页数
		// rp:每页显示多少条
		// sortname：排序的字段名称
		// sortorder: 排序的方向；比如：asc，desc；
		// query : 查询的条件
		// qtype ：查询的类型
		
		String rp=request.getParameter("rp"); //每页显示的数据数
		String pageString=request.getParameter("page");//获取 flexgrid传过来的页数。
		String query=request.getParameter("query");//获取 查询的条件
		query = java.net.URLDecoder.decode(query , "UTF-8");//解码
		String error = request.getParameter("ss");
		//error.indexOf("23");
		
		String qtype=request.getParameter("qtype");//获取 查询的类型
		String sortorder=request.getParameter("sortorder");//获取 查询的类型
		if(pageString == null || pageString.length() == 0) {
			pageString = "1";
		}
		StringBuffer hql = new StringBuffer(" from com.tueye.entity.Admin ");
		if(StringUtils.isNotEmpty(query)) hql.append(" where "+query);
		//if(StringUtils.isNotEmpty(query)) hql.append(" where "+qtype+" ='"+query+"'");
		if(StringUtils.isNotEmpty(qtype))hql.append("   order   by "+qtype);
		if(StringUtils.isNotEmpty(sortorder))hql.append("   "+sortorder);
		System.out.println("##########hql:"+hql.toString());
		Page pageModel = adminInfoService.pagedQueryByHQL(hql.toString(), Integer.valueOf(pageString), Integer.valueOf(rp), null);
		
		Map pageInfo = new HashMap();
		pageInfo.put("page", new Integer(pageString));
		pageInfo.put("total", pageModel.getTotalCount());
		//生成json字符串
		String jsonStr = getJsonString((List)pageModel.getResult(),pageInfo);
		log.info("###############:"+jsonStr);
		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(jsonStr);
		
/*		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setHeader("Pragma", "no-cache");
		response.getWriter().write(jsonStr);
		response.getWriter().flush();
		response.getWriter().close();*/
		
		return null;
	}
	
	@RequestMapping(params = "action=save")
	public String save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		String mainId = (String) request.getParameter("id");
		String type = (String)request.getParameter("type");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String byname = request.getParameter("byname");
		//新增
		Admin admin = new Admin();
		admin.setId(new UUIDGenerator().getUUID());
		admin.setUsername(username);
		admin.setPassword(password);
		admin.setByname(byname);
		admin.setIsValid(0);
		admin.setSys_time(new Date());
		adminInfoService.addAdmin(admin);
		
		return null;
	}
	
	/**
	 * type表示操作类型
	 * new/null 新建
	 * maindi != null 并且type =copy  复制
	 * maindi != null 并且type =edit  修改
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "action=saveDetail")
	public String saveDetail (HttpServletRequest request, HttpServletResponse response) throws Exception {
			String retult = "true";
			try{
				request.setCharacterEncoding("UTF-8");
				String mainId = (String) request.getParameter("id");
				String type = (String)request.getParameter("type");
				String username = request.getParameter("username");
				String password = request.getParameter("password");
				String byname = request.getParameter("byname");
				//修改
				if(StringUtils.isNotEmpty(mainId)&&type.toLowerCase().equalsIgnoreCase("edit")){
					Admin admin = new Admin();
					admin = adminInfoService.getAdminById(mainId);
					admin.setUsername(username);
					admin.setPassword(password);
					admin.setByname(byname);
					admin.setIsValid(0);
					admin.setSys_time(new Date());
					adminInfoService.addAdmin(admin);
				}else{
					//复制
					if(StringUtils.isNotEmpty(mainId)&&type.toLowerCase().equalsIgnoreCase("copy")){
						Admin admin = new Admin();
						admin = adminInfoService.getAdminById(mainId);
						admin.setId(new UUIDGenerator().getUUID());
						admin.setUsername(username);
						admin.setPassword(password);
						admin.setByname(byname);
						admin.setIsValid(0);
						admin.setSys_time(new Date());
						adminInfoService.addAdmin(admin);
					}else{
						//新增
						Admin admin = new Admin();
						admin.setId(new UUIDGenerator().getUUID());
						admin.setUsername(username);
						admin.setPassword(password);
						admin.setByname(byname);
						admin.setIsValid(0);
						admin.setSys_time(new Date());
						adminInfoService.addAdmin(admin);
					}
				}
			}catch (RuntimeException e) {
				log.error(e.getMessage());
				retult = "false";
			}
			response.getWriter().print(retult);
		return null;
	}
	@RequestMapping(params = "action=initDetail")
	public ModelAndView initDetail (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		String mainId = (String) request.getParameter("id");
		String type = (String)request.getParameter("type");
		ModelAndView mav = new ModelAndView("/pages/admin/addAdmin");
		Admin admin = new Admin();
		//修改
		if(StringUtils.isNotEmpty(mainId)&&type.toLowerCase().equalsIgnoreCase("edit")){
			admin = adminInfoService.getAdminById(mainId);
		}else{
			//复制
			if(StringUtils.isNotEmpty(mainId)&&type.toLowerCase().equalsIgnoreCase("copy")){
				admin = adminInfoService.getAdminById(mainId);
				admin.setId(new UUIDGenerator().getUUID());
			}else{
				//新增
				admin = new Admin();
			}
		}
		mav.addObject("type", type);
		mav.addObject("admin",admin);
		return mav;
	}
	
	@RequestMapping(params = "action=delete")
	public void delete (HttpServletRequest request, HttpServletResponse response){
		
		String retult = "true";
		try {
			request.setCharacterEncoding("UTF-8");
			String id = request.getParameter("id");
			adminInfoService.delAdmin(id);
			response.getWriter().print("true");
		} catch (Exception e) {
			log.error("#####出错了"+e.getMessage());
			
		}
		
	}
	
	/**
	 * @param list
	 * @param pageInfo
	 * @return
	 */
	private String getJsonString(List list, Map pageInfo) {

		List mapList = new ArrayList();   
		for (int i = 0; i < list.size(); i++) {
			Admin admin = (Admin) list.get(i);
			Map cellMap = new HashMap();
			cellMap.put("numid", i+1);
    		cellMap.put("cell", new Object[]{
    				
    				admin.getId(),
    				i+1,
    				admin.getUsername(),
    				admin.getByname(),
    				admin.getLoginName(),
    				admin.getPassword(),
    				admin.getEmail(),
    				admin.getIsValid(),
    				DateUtils.getDate2Str("yyyy-MM-dd HH:mm",admin.getSys_time())
    				});
    				mapList.add(cellMap);
		}
    	pageInfo.put("rows", mapList);
    	com.tueye.ajax.json.JSONObject object = new com.tueye.ajax.json.JSONObject(pageInfo);
    	return object.toString();
	}
	/**
	 * 
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unused")
	private Object getJsonString(Object obj){
		
		JSONObject json = JSONObject.fromObject(obj);
		log.info("############# "+json);
		return json;
	}
	
}
